<?php
/**
 *
 * (model)
 */
namespace App\Models\OverSeasBa;

use App\Models\Basics\AmazonAccount;
use App\Models\Basics\SysPlat;
use App\Models\Product\ProductClassify;
use Illuminate\Database\Eloquent\Model;
use App\Models\Product\ProductSku;
use App\Models\Product\ProductAmazonSku;
class RemovaleInventoryFNSku extends Model
{
    protected $table = 'os_b_removale_inventory_fnsku';

    protected $guarded = [];

    public $timestamps = false;

    public function warehouse(){
        return $this->belongsTo(Warehouse::class,'warehouse_id');
    }

    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public static function getInstantAndTransit($warehouseIds,$pSkuId,$platId = 0){
        $query = self::query();
        $query->selectRaw('sum(IFNULL(instant,0)) as instant,sum(IFNULL(transit,0)) as transit');
        if ($warehouseIds) $query->whereIn('warehouse_id', $warehouseIds);
        if ($pSkuId) $query->where('psku_id', $pSkuId);
        if ($platId > 0) $query->where('plat_id',$platId);

        return $query->first();
    }

    public static function getInstant($warehouseId,$accountId,$fnSku,$platId = 0){
        $query = self::query();
        if ($warehouseId)  $query->where('warehouse_id', $warehouseId);
        if ($accountId) $query->where('account_id', $accountId);
        if ($fnSku) $query->where('fnsku', $fnSku);
        if ($platId > 0) $query->where('plat_id', $platId);

        $instant = $query->value('instant');
        return $instant ?: 0;
    }

    public function skuClassify(){
        return $this->hasOneThrough(
            ProductClassify::class,
            ProductSku::class,
            'id',//中间表
            'id',//目标表
            'psku_id',//当前模型
            'classify_id'//中间表
        );
    }

    public static function initRelatedData($accountId,$pSkuId,$fnsku,$platId = 0){
        $countryIds = AmazonAccount::getCountriesById($accountId);
        return ProductAmazonSku::query()->select('plat_id','psku_id','account_id','fnsku')
            //->where('plat_id',$platId)
            //->where('fnsku','<>',$fnsku)
            ->where('psku_id',$pSkuId)
            ->whereIn('country_id',$countryIds)
            ->groupBy(['account_id','fnsku'])
            ->get();
    }
}
